/* global window */
import { message } from 'antd'
import api from 'api'
import modelExtend from 'dva-model-extend'
import { pathMatchRegexp } from 'utils'
import { pageModel } from 'utils/model'

const { workergetAllProject, workergetDevices, workerInputImei } = api
const regionstate = {
  choosedproject: 'all',
  projects: [],
}
export default modelExtend(pageModel, {
  namespace: 'workers',

  state: {
    ...regionstate,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (pathMatchRegexp('/workers', location.pathname)) {
          let payload = { page: 1, pageSize: 10, workerproject: 'all' }
          if (location.query) {
            const { page, pageSize, workerproject } = location.query
            payload = {
              ...payload,
              ...(page != undefined && pageSize != undefined
                ? { page, pageSize }
                : {}),
              ...(workerproject != undefined ? { workerproject } : {}),
            }
          }
          dispatch({
            type: 'updateState',
            payload: {
              ...payload,
              choosedproject: payload.workerproject,
            },
          })
        }
      })
    },
  },

  effects: {
    *clearstore({ payload = {} }, { call, put, select }) {
      yield put({
        type: 'updateState',
        payload: {},
      })
    },
    *workergetAllProject({ payload = {} }, { call, put }) {
      const { result } = yield call(workergetAllProject, payload)
      yield put({
        type: 'updateState',
        payload: {
          projects: result,
        },
      })
    },
  },

  reducers: {},
})
